import React, { useEffect } from 'react';
import style from './01.less';
export default function Proto() {
    let canvas, context, readout, spritesheet;
    useEffect(() => {
        canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        readout = document.getElementById('readout'),
        spritesheet = new Image();

        spritesheet.src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.feehi.com%2Fuploads%2Farticle%2Frobot%2F2017%2F06%2F5952814af34cc.jpg&refer=http%3A%2F%2Fwww.feehi.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617112125&t=808bc3d27845a61a51b9847684e20648';

        spritesheet.onload = function(e) {
            drawSpritesheet();
        };

        canvas.onmousemove = function(e) {
            let loc = windowToCanvas(canvas, e.clientX, e.clientY);

            drawBackground();
            drawSpritesheet();
            drawGuidelines(loc.x, loc.y);
            updateReadout(loc.x, loc.y);
        };

        drawBackground();

    });

    function windowToCanvas(canvas, x, y) {
        let bbox = canvas.getBoundingClientRect();
        return {
            x: x - bbox.left * (canvas.width / bbox.width),
            y: y - bbox.top * (canvas.height / bbox.height)
        };
    }

    function drawBackground() {
        let VERTICAL_LINE_SPACING = 12,
            i = context.canvas.height;
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.strokeStyle = 'lightgray';
        context.lineWidth = .5;

        while (i > VERTICAL_LINE_SPACING * 4) {
            context.beginPath();
            context.moveTo(0, i);
            context.lineTo(context.canvas.width, i);
            context.stroke();
            i -= VERTICAL_LINE_SPACING;
        }
    }

    function drawSpritesheet() {

        context.drawImage(spritesheet, 0, 0);
    }

    function drawGuidelines(x, y) {
        context.strokeStyle = 'rgba(0, 0, 230, 0.8)';
        context.lineWidth = .5;
        drawVerticalLine(x);
        drawHorizontalLine(y);
    }

    function updateReadout(x, y) {
        readout.innerText = `(${x.toFixed(0)}),${y.toFixed(0)}`;
    }

    function drawHorizontalLine(y) {
        context.beginPath();
        context.moveTo(0, y + 0.5);
        context.lineTo(context.canvas.width, y + 0.5);
        context.stroke();
    }

    function drawVerticalLine(x) {
        context.beginPath();
        context.moveTo(x + 0.5, 0);
        context.lineTo(x + 0.5, context.canvas.height);
        context.stroke();
    }

    return (
        <>
            <div id="readout" className={style.readout}></div>
            <canvas id="canvas" className={style.canvas3} width="500" height="250">
            </canvas>
        </>
    );
}